package com.mxpio.erp.common.listener;

import com.mxpioframework.camunda.service.BpmnFlowService;
import com.mxpioframework.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @Author : wpp
 * @Datetime : 2024/5/27 16:57
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc :
 */
@Component
@Slf4j
class MyBpmnListener {
    @Autowired
    private MessageService messageService;
    @Autowired
    private BpmnFlowService bpmnFlowService;
    @EventListener
    public void onTaskEvent(DelegateTask delegateTask) {
        // handle mutable task event
        String eventName = delegateTask.getEventName();
        log.info(eventName);
        if (TaskListener.EVENTNAME_ASSIGNMENT.equals(eventName)){
            // 获取任务待办人信息
            String assignee = delegateTask.getAssignee();
            // 获取需要的信息，如任务标题、描述等
            String taskName = delegateTask.getName();
            String processInstanceId = delegateTask.getProcessInstanceId();
            HistoricProcessInstance historicProcessInstance = bpmnFlowService.getHistoricProcessInstanceById(processInstanceId);
            ProcessDefinitionEntity processDefinition = ((TaskEntity) delegateTask).getProcessDefinition();
            String title = processDefinition.getName();//默认取流程定义名称
            if (historicProcessInstance!=null){
                String titleByInstanceId = bpmnFlowService.getTitleByInstanceId(historicProcessInstance.getId());
                if (StringUtils.isNotBlank(titleByInstanceId)){
                    title = titleByInstanceId;
                }
            }
            log.info("任务提醒：任务 '{}' 分配给了 '{}', 流程实例ID: {}", taskName, assignee, processInstanceId);
            messageService.sendMessage(new String[]{"innerMsg"},"admin",new String[]{assignee},"工作流审核任务提醒", title+"："+taskName);
        }
    }
}
